import { Token } from "../../../service/token.js";
var app = getApp(), u = app.require("utils/util.js"), a = app.require("utils/api.js"), o = app.require("utils/onfire.js"), h = app.require("utils/http.js"), n = app.require("utils/enums");
var rate = 0; //分辨转换
var floatTop = 0; //悬浮高度

Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    indicatorColor: '#82AAFB',
    dialogType: null,
    userInfo: null,
    bannerList:[],
    cateList:n.cateList,
    handpickTitle:'精选品牌',
    handpickImage:null,
    handpickProduct:[],
    hotProductList:[],
    cateGoryList: [],
    showTabNum:3,
    tabs: [],
    isShowFloatTab:false,
    scrollTop:0,
    scrollHeight:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getScrollTop();
  },
  onShow:function(){
    console.log(a.storeId);
    this.verify();    
  },
  
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh() {
    var t = this;
    // 增加下拉刷新数据的功能
    this.getStorIndexList(), this.getCateGory();
    // 隐藏导航栏加载框
    wx.hideNavigationBarLoading();
    // 停止下拉动作
    wx.stopPullDownRefresh();
  },

  verify:function(){
    var t = this;
    app.getToken();
    if (wx.getStorageSync('userInfo')) {
      t.data.userInfo = wx.getStorageSync('userInfo'),
      t.getStorIndexList(), t.getCateGory();
    } else {
      app.callAuthorize(function (userinfo) {
        t.getStorIndexList(userinfo), t.getCateGory()
      });
    }
  },
  // 获取首页商品信息
  getStorIndexList:function(userinfo){
    var t = this; 
    var data = {
      store_id: a.storeId,
      uid: userinfo ? userinfo.uid : t.data.userInfo.uid
    };    
    h.postReq(a.getStorIndex,data,function(res){
      if(res.code == 0){        
        var list = res.data.custom_field_list;
        var banner = new Array();
        var product = new Array();
        var aboutus = new Array();
        var pickBanner = new Array();
        Object.keys(list).forEach(function (i, v) {
          if (list[i].field_type.length > 0) {
            if (list[i].field_type == 'image_ad' && !list[i].image_type) {
              t.data.bannerList = list[i]['content']['nav_list'];
            }
            if (list[i].field_type == 'image_ad' && list[i].image_type == 'advert') {
              t.data.handpickImage = list[i]['content']['nav_list'][0].image; 
            }
            if (list[i].field_type == 'goods') {
              t.data.handpickProduct = list[i]['content']['goods'];
            }
            if (list[i].field_type == 'goods_group1') {
              t.data.hotProductList = list[i]['goods_group_list'][0]['product_list'];
            }           
          }
        })
        t.setData({ 
          bannerList: t.data.bannerList,
          handpickImage: t.data.handpickImage, 
          handpickProduct: t.data.handpickProduct,
          hotProductList: t.data.hotProductList
        });        
      }else if(res.code == 401){
        console.log(res.message),
        app.callAuthorize(function (userinfo) {
          t.getStorIndexList(userinfo), t.getCateGory()
        });
      }
    });
  },
  // 获取分类列表
  getCateGory: function () {
    var t = this;
    var data = {};   
    h.noLoadReq(a.getCateGoryUrl, data, 'POST' ,function (res) {
      if (res.code == 0) {        
        t.setData({ cateGoryList: [] }); 
        t.data.cateGoryList = [{ cat_id: 0, cat_name: '热卖精选' }],       
        t.data.cateGoryList = t.data.cateGoryList.concat(res.data);
        t.setData({ cateGoryList: t.data.cateGoryList });
      }else {
        console.log(res.message)
      }
    });
  },
  // tab切换
  tabOnClick:function(e){
    var t = this;
    var key = e.detail.key;
    var checkedTab = t.data.cateGoryList[key];
    var title = checkedTab.cat_name;
    var value = checkedTab.cat_id;
    if(value == 0){
      return;
    }
    app.globalData.cat_id = title;
    app.globalData.value = value;
    wx.switchTab({
      url: "/pages/category/index/index"
    }); 
  },
  changeShowTab:function(){
    var t = this;
    var len = t.data.cateGoryList.length;
    t.setData({
      showTabNum:len
    });
  },
  // 搜索列表页面
  goSearch:function(){
    wx.navigateTo({
      url: '../../category/index/list?title=全部药品',
    })
  },
  // 切换到分类页面
  toCate:function(e){      
    var title = e.currentTarget.dataset.title;
    var value = e.currentTarget.dataset.value;
    app.globalData.cat_id = title;
    app.globalData.value = value;
    wx.switchTab({
      url: "/pages/category/index/index"
    });  
  },
  // 商品详情
  proudctInfo:function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'info?id='+ id
    })
  },
  // 加入购物车
  addCart:function(e){
    var t = this;
    var product_id = e.currentTarget.dataset.id
    var quantity = 1;
    var data = {
      store_id: a.storeId, uid: t.data.userInfo.uid, product_id: product_id, quantity: quantity
    };
    // 加入购物车流程     
    h.noLoadReq(a.addCart, data, 'POST' ,function (res) {
      if (res.code == 0) {
        u.success('成功加入购物车');
      } else {
        u.toast(res.message);
      }
    });  
  },

  /**
   * 获得滑动导致悬浮开始的高度
   * @return {[type]} [description]
   */
  getScrollTop: function () {
    var that = this;
    if (wx.canIUse('getSystemInfo.success.screenWidth')) {
      wx: wx.getSystemInfo({
        success: function (res) {
          console.log(res);
          rate = res.screenWidth / 750;
          floatTop = 1396 * rate;
          // console.log(rate,floatTop);
          that.setData({
            scrollTop: 1396 * res.screenWidth / 750,
            scrollHeight: res.screenHeight / (res.screenWidth / 750) - 128,
          });
        }
      });
    }
  },

  /**
    * 生命周期函数--监听页面加载
    */
  onPageScroll: function (event) {
    var scrollTop = event.scrollTop;
    if (scrollTop >= floatTop && !this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: true,
      });
    } else if (scrollTop < floatTop && this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: false,
      });
    }
  },
})